<template>
  <view class="setting-container" :style="{height: `${windowHeight}px`}">
    <view class="menu-list">
      <view class="list-cell list-cell-arrow" @click="handleToPwd">
        <view class="menu-item-box">
          <view class="iconfont icon-password menu-icon"></view>
          <view>修改密码</view>
        </view>
      </view>
      <view class="list-cell list-cell-arrow" @click="handleToUpgrade">
        <view class="menu-item-box">
          <view class="iconfont icon-refresh menu-icon"></view>
          <view>检查更新{{ msgVersion }}</view>
        </view>
      </view>
    <!--  <view class="list-cell list-cell-arrow" @click="handleCleanTmp">
        <view class="menu-item-box">
          <view class="iconfont icon-clean menu-icon"></view>
          <view>清理缓存</view>
        </view>
      </view> -->

	  <view class="list-cell list-cell-arrow" @click="getCurrentVersion">
	    <view class="menu-item-box">
	      <view class="iconfont icon-clean menu-icon"></view>
	      <view>版本号{{ oldVersion }}</view>
	    </view>
	  </view>
	  <view>{{ result }}</view>
	  
	  
	  <uni-forms-item class="list-cell list-cell-arrow" label="电子秤" name="scaleId" >
	  	  <uni-data-select
	  		v-model="value"
	  		:localdata="range"
	  		disabled
	  	@change="elecSelectedFun"
	  	
	  	  ></uni-data-select>
	  </uni-forms-item>
    </view>
	
	<!-- <view>{{ result3 }}</view>
	<view>{{ result2 }}</view> -->
    <view class="cu-list menu">
      <view class="cu-item item-box">
        <view class="content text-center" @click="handleLogout">
          <text class="text-black">退出登录</text>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
	
	import { checkVersion ,getWeight,  getElecSelected, getElecStatus, savaElecSelected, getCurrentUserElec} from '@/api/longyi/version'
	let downloadTask = null;
  export default {
    data() {
      return {

		 value: null,
		 range: [],
		 elecInfo: [],
		 elecSelected: '',
		 preInfoData: {
		 	id: '',
		 	weight: '',
		 	msg: ''
		 }, 
		  
        windowHeight: uni.getSystemInfoSync().windowHeight,
		formData: {
		    currentVersion: getApp().globalData.config.appInfo.version,
			scaleId: ''
		  },
		lastVersion: '',
		downloadUrl: '',
		content: '',
		result: '',
		result2:'',
		result3: '',
		oldVersion: '',
		newVersion: '',
		msgVersion:'',
		statusSelected: {
			ip: '',
			port: ''
		},
		ipPortSelected: {
		  id: 0,
		  name: '',
		  ip: '',
		  port: 0
		},
      }
    },
	onReady() {
		this.getType()
		
		this.oldVersion = getApp().globalData.config.appInfo.version
		checkVersion(this.formData).then(response => {
			if (response.data) {
			  // 数据存在
			  this.result2 = response.data
			  this.lastVersion = response.data.version;			  
			  this.downloadUrl = response.data.downloadUrl;
			  this.content = response.data.content;
			  let current = Number(this.formData.currentVersion.replace(/\./g,""));
			  let last = Number(this.lastVersion.replace(/\./g,""));
			  if(current < last){
				 // this.msgVersion="    "+"           需要更新"
			  	console.log("需要更新")
			  }
			} 			
		})
	},

	
    methods: {
      handleToPwd() {
        this.$tab.navigateTo('/pages/mine/pwd/index')
      },
      handleToUpgrade() {
		  this.updateVersion();
		  // this.checkVersion();
		  // this.$tab.navigateTo('/pages/mine/checkUpdate/index')
        // this.$modal.showToast('模块建设中~')
      },
	  getCurrentVersion(){
	  	this.oldVersion = getApp().globalData.config.appInfo.version
	  },
	  
	  // 电子秤查询
	  getType() {
		//  console.log(1111)
	    getWeight().then(response => {
	  	 this.elecInfo = response.data
	  	 getElecSelected().then(response2 => {
	  	 	this.elecSelected = response2.data
	  	 	for(let i in this.elecInfo){
	  	 	  this.range.push({ value: this.elecInfo[i].id, text: this.elecInfo[i].name })
	  	 	  if(this.elecSelected.id === this.elecInfo[i].id){
	  	 		this.value = this.elecSelected.id
	  	 		this.formData.scaleId = this.elecSelected.id
	  	 		this.statusSelected.port = this.elecSelected.port
	  	 		this.statusSelected.ip = this.elecSelected.ip
	  	 		getElecStatus(this.statusSelected).then(response => {
	  	 			this.formData.communicateStatus = response.data
	  	 		})
	  	 	  } 
	  	 	}
	  	 })
	    })
	    
	    getCurrentUserElec(this.statusSelected).then(response => {
	  	//	 console.log("222"+response.data)
	  		this.value = response.data.name
	  		this.formData.scaleId = response.data.id
	  		this.statusSelected.port = response.data.port
	  		this.statusSelected.ip = response.data.ip
	  		getElecStatus(this.statusSelected).then(response => {
	  			this.formData.communicateStatus = response.data
	  		})
	  		this.formData.scaleName= response.data.name
	  		
	    })
	    
	  },
	  /** 选择电子秤 */
	   elecSelectedFun (value) {
	      //获取选中的电子秤信息
	      for(let i in this.elecInfo){
	        if(value === this.elecInfo[i].id){
	          this.ipPortSelected.id = this.elecInfo[i].id
	          this.ipPortSelected.port = this.elecInfo[i].port
	          this.ipPortSelected.ip = this.elecInfo[i].ip
	          this.ipPortSelected.name = this.elecInfo[i].name
	  		this.ipPortSelected.scaleId = this.elecInfo[i].id
	          this.statusSelected.port = this.elecInfo[i].port
	          this.statusSelected.ip = this.elecInfo[i].ip
	        } 
	      }
	  	this.formData.scaleId= this.ipPortSelected.scaleId
	  	savaElecSelected(this.ipPortSelected).then(response => {
	  		getElecStatus(this.statusSelected).then(response2 => {
	  			this.formData.communicateStatus = response2.data
	  			this.inpFocus = true
	  		})
	  	})
	    },
	  
	  // 更新版本
	  updateVersion() {
	
	// 获取
		checkVersion(this.formData).then(response => {
			if (response.data) {
			  // 数据存在
			  this.result2 = response.data
			  this.lastVersion = response.data.version;
			  
			  this.downloadUrl = response.data.downloadUrl;
			  this.content = response.data.content;
			  let current = Number(this.formData.currentVersion.replace(/\./g,""));
			  let last = Number(this.lastVersion.replace(/\./g,""));
			  console.log(current+"---"+last)
			  if(current < last){
			  	this.showUpdateModal()
			  }
			} else {
				this.msgVersion='：目前最新版本'
				//console.log("已经更新")
			  // 数据不存在或为空
			}
			
			
		})
	  },
	  showUpdateModal() {
		  uni.showModal({
			  title: '发现新版本',
			  content: this.content,
			  success: (res) => {
				  if (res.confirm) {
					  this.downloadPackage()
				  }
			  }
		  });
	  },
	  downloadPackage() {
	  	uni.showLoading({
			title: '更新中……'
		})
		downloadTask = uni.downloadFile({//执行下载
			url: this.downloadUrl, //下载地址
			success: downloadResult => {//下载成功
				uni.hideLoading();
				this.result3 = downloadResult.tempFilePath
				if (downloadResult.statusCode == 200) {
					//开始安装
					plus.runtime.install(downloadResult.tempFilePath, {
						force: false  
					}, function() {  
						console.log('install success...');
						plus.runtime.restart();
					}, function(e) {  
						console.error('install fail...',e);  
						uni.showToast({
							title: '升级失败',
							icon:'none'
						});
					});
				}else{
					downloadTask = null;
					this.$modal.showToast('下载失败')
					// downloadTask.abort()//中断下载任务  
				}
			},
			fail:function(e) {
				uni.showToast({
					title: '下载失败:'+e.errMsg,
					icon:'none'
				});
			}
		});
	  },
      handleCleanTmp() {
        this.$modal.showToast('模块建设中~')
      },
      handleLogout() {
        this.$modal.confirm('确定注销并退出系统吗？').then(() => {
          this.$store.dispatch('LogOut').then(() => {
            this.$tab.reLaunch('/pages/index')
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .page {
    background-color: #f8f8f8;
  }

  .item-box {
    background-color: #FFFFFF;
    margin: 30rpx;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    padding: 10rpx;
    border-radius: 8rpx;
    color: #303133;
    font-size: 32rpx;
  }
</style>
